#!/usr/bin/env python3
# 在服务器运行：python3 server_upload.py
# 监听 8080，POST /upload 保存文件到 /var/www/html
import os, cgi, http.server, socketserver
UPLOAD_DIR = '/var/www/html'
os.makedirs(UPLOAD_DIR, exist_ok=True)

class Handler(http.server.SimpleHTTPRequestHandler):
    def do_POST(self):
        if self.path == '/upload':
            form = cgi.FieldStorage(fp=self.rfile, headers=self.headers,
                                    environ={'REQUEST_METHOD':'POST'})
            if 'file' in form:
                item = form['file']
                with open(os.path.join(UPLOAD_DIR, item.filename), 'wb') as f:
                    f.write(item.file.read())
                self.send_response(200)
                self.end_headers()
                self.wfile.write(b'ok')
                return
        self.send_error(404)

socketserver.TCPServer.allow_reuse_address = True
with socketserver.TCPServer(('0.0.0.0', 8080), Handler) as httpd:
    print("上传接口已启动：http://服务器IP:8080/upload")
    httpd.serve_forever()